#!/bin/bash

# Verify we're in the correct workspace
if [ ! -d "/workspace/ABC" ]; then
    echo "Error: Expected /workspace/ABC directory not found"
    exit 1
fi

# Check required tools
if ! command -v cmake &> /dev/null; then
    echo "Error: cmake not found. Please install CMake."
    exit 1
fi

if ! command -v dotnet &> /dev/null; then
    echo "Error: dotnet not found. Please install .NET SDK."
    exit 1
fi

# Set directories
BASE_DIR="/workspace/ABC"
BUILD_DIR="$BASE_DIR/build"

# Clean previous builds
echo "Cleaning previous builds..."
rm -rf "$BUILD_DIR"/*

# Build PrimeCore
echo "Building PrimeCore..."
mkdir -p "$BUILD_DIR/PrimeCore"
cd "$BASE_DIR/PrimeCore" && \
cmake -B "$BUILD_DIR/PrimeCore" -DCMAKE_BUILD_TYPE=Release && \
cmake --build "$BUILD_DIR/PrimeCore" --config Release --target PrimeCore
if [ $? -ne 0 ]; then
    echo "Error: Failed to build PrimeCore"
    exit 1
fi

# Build EconCore
echo "Building EconCore..."
mkdir -p "$BUILD_DIR/EconCore"
cd "$BASE_DIR/EconCore" && \
cmake -B "$BUILD_DIR/EconCore" -DCMAKE_BUILD_TYPE=Release && \
cmake --build "$BUILD_DIR/EconCore" --config Release --target EconCore
if [ $? -ne 0 ]; then
    echo "Error: Failed to build EconCore"
    exit 1
fi

# Build AgentCore
echo "Building AgentCore..."
mkdir -p "$BUILD_DIR/AgentCore"
cd "$BASE_DIR/AgentCore" && \
cmake -B "$BUILD_DIR/AgentCore" -DCMAKE_BUILD_TYPE=Release && \
cmake --build "$BUILD_DIR/AgentCore" --config Release --target AgentCore
if [ $? -ne 0 ]; then
    echo "Error: Failed to build AgentCore"
    exit 1
fi

# Copy all libraries to common directory
echo "Copying libraries..."
mkdir -p "$BUILD_DIR/libs"
find "$BUILD_DIR" -name "*.so" -exec cp {} "$BUILD_DIR/libs/" \;
if [ $? -ne 0 ]; then
    echo "Error: Failed to copy libraries"
    exit 1
fi

# Build C# application
echo "Building C# application..."
cd "$BASE_DIR/PrimeCalculator" && \
dotnet publish -c Release -o "$BUILD_DIR" --self-contained false
if [ $? -ne 0 ]; then
    echo "Error: Failed to build C# application"
    exit 1
fi

echo ""
echo "Build completed successfully!"
echo "To run the application:"
echo "  cd $BUILD_DIR"
echo "  dotnet PrimeCalculator.dll"